<?php
/**
 * Author: yann
 * QQ: 9197313
 * Date: 2018/11/26 0026
 * Time: 下午 6:04
 */

namespace app\api\controller;


use app\model\MpFans;
use app\model\Token;
use EasyWeChat\Factory;
class Login extends Base
{
    public function login(){
        $code = $this->request->post('code','');
        $encrypted_data = $this->request->post('encrypted_data','');
        $iv = $this->request->post('iv','');
        try {
            $app = Factory::miniProgram([
                'app_id' => 'wx15ccaeb7366b1ebf',
                'secret' => 'f5b458b2c79d9aa956ea61e8cfb626c1',
                'response_type' => 'array'
            ]);
            $data = $app->auth->session($code);

            $result = MpFans::where(['openid'=>$data['openid']])->find();
            if(!$result){
                MpFans::create([
                    'openid' => $data['openid'],
                    'is_subscribe' => 0,
                    'subscribe_time' => time()
                ]);
                $openid = $data['openid'];
            }else{
                $openid = $result['openid'];
            }

            if($encrypted_data && $iv){
                $res = $app->encryptor->decryptData($data['session_key'], $iv, $encrypted_data);
                MpFans::update([
                    'nickname' => $res['nickName'],
                    'sex' => $res['gender'],
                    'headimgurl' => $res['avatarUrl'],
                    'country' => $res['country'],
                    'province' => $res['province'],
                    'city' => $res['city'],
                    'is_subscribe' => 1,
                ],['openid'=>$res['openId']]);
            }

            session('openid', $openid);
            $token = $this->buildToken($openid,$data['session_key']);
            return $this->buildSuccess(['token'=>$token]);

        } catch (\Exception $e) {
            return $this->buildFailed($e->getCode(),$e->getMessage());
        }
    }


    private function buildToken($openid,$session_key){

        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' .$session_key;
        $chars = str_shuffle($chars);
        $token = substr($chars, 3, 32);
        $res = Token::where(['token' => $token])->count();
        if(!$res){
            $time = time();
            if(Token::where(['openid'=>$openid])->count()){
                Token::update([
                    'token' => $token,
                    'session_key' => $session_key,
                    'create_time' => $time,
                    'expire_time' => $time + 3600 * 24
                ],['openid'=>$openid]);
            }else{
                Token::create([
                    'token' => $token,
                    'openid' => $openid,
                    'session_key' => $session_key,
                    'create_time' => $time,
                    'expire_time' => $time + 3600 * 24
                ]);
            }
            return $token;
        }else{
            $this->buildToken($openid,$session_key);
        }
    }

}
